package com.neueedu.android.ticket;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.neueedu.android.R;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TicketActivity1 extends AppCompatActivity {

    private ListView lvStations;
    private LetterListView letterListView;
    //数据（容器）
    List<Map<String, Object>> data = new ArrayList<>();

    StationListViewAdapter stationListViewAdapter ;
    ArrayList<Station> allStations = new ArrayList<>();//数据
    private Map<String,Integer>  letterIndex = new HashMap();

    ProgressDialog progressDialog;
    //UI 现成
    Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);


            //1 跟新界面
            if(msg.arg1 == 1){

                stationListViewAdapter.notifyDataSetChanged();
                progressDialog.dismiss();
            }else  if(msg.arg1 == 2) {  //2 打印一下 uomg
                String json = (String) msg.obj;
                Toast.makeText(TicketActivity1.this, json, Toast.LENGTH_SHORT).show();

            }


        }
    };





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ticket1);

        lvStations = findViewById(R.id.lvStations);
        letterListView = findViewById(R.id.letterListView);


        letterListView.setOnTouchingLetterChangedListener(new LetterListView.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String letter) {
                if( letterIndex.containsKey(letter)){
                    Integer letterFirstIndex = letterIndex.get(letter);

                    Toast.makeText(TicketActivity1.this, "letter:"+letter, Toast.LENGTH_SHORT).show();
                    lvStations.setSelection(letterFirstIndex);
                }

            }
        });

        initData();
//        String[] from = new String[]{"letter","name"};
//        int to[] = {R.id.tvLetter  ,  R.id.tvStationName};
//        simpleAdapter = new SimpleAdapter(this,data,R.layout.activity_ticket1_stations_item ,from,to);




        stationListViewAdapter = new StationListViewAdapter(allStations);

        lvStations.setAdapter(stationListViewAdapter);

        lvStations.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Station station = allStations.get(position);


                Intent intent = new Intent();
                intent.putExtra("stationName",station.getStation_name());
                setResult(200,intent);
                finish();
            }
        });
    }

    private void initData() {


        progressDialog =ProgressDialog.show(this,"提示","加载中,请稍等",true,false);
        progressDialog.show();


        //开始发起网络请求
        new Thread(){
            @Override
            public void run() {
                super.run();
//                for (int j = 0; j <  3; j++) {
//
//                    try {
//                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//
//                }

//               JDBCTemplate   RestTemplte

                //原生的
//                HttpURLConnection urlConnection


//                okhttp


                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder() .url("https://api.uomg.com/api/comments.163?format=json").addHeader("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36")  .build();

                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                        String json = response.body().string();
                        Message msg = handler.obtainMessage();
                        msg.arg1 = 2;
                        msg.obj = json;
                        handler.sendMessage(msg);




                    }
                });




                    allStations.clear();

                    allStations.addAll(StationUtils.getAllStations(TicketActivity1.this));

                    Message msg = handler.obtainMessage();
                    msg.arg1 = 1;
//                    msg.what
//                    msg.arg1
//                    msg.arg2
                    handler.sendMessage(msg);


                    for (int i = 0; i < allStations.size(); i++) {
                        Station station = allStations.get(i);

                        String letter = station.getSort_order();//车站的首字母

                        if(!letterIndex.containsKey(letter)){
                            letterIndex.put(letter,i);
                        }
                    }




            }
        }.start();

        //网络请求结束















    }


    /**
     * 自定义适配器
     */
    class StationListViewAdapter extends BaseAdapter{


        private List<Station> list ;

        public StationListViewAdapter(List<Station> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {


            Station data = list.get(position);



            View v = null;
            ViewHolder viewHolder ;
            //是否使用缓存
            if( convertView == null){
                //使用当行布局资源文件 通过LayoutInflater 渲染一个单行的View
                v = getLayoutInflater().inflate(R.layout.activity_ticket1_stations_item,null);

                viewHolder = new ViewHolder();
                viewHolder.tvLetter  =  v.findViewById(R.id.tvLetter);
                viewHolder.tvStationName  =  v.findViewById(R.id.tvStationName);
                v.setTag(viewHolder);

            }else{
                v = convertView;
                viewHolder = (ViewHolder) v.getTag();

            }


            Integer letterFirstIndex = letterIndex.get(data.getSort_order());

            //首字母显示出来
            if(letterFirstIndex.intValue() == position){
                viewHolder.tvLetter.setVisibility(View.VISIBLE);
            }

            viewHolder.tvLetter.setText(data.getSort_order());
            viewHolder.tvStationName.setText(data.getStation_name());



            return v;
        }


        class ViewHolder{
            TextView tvLetter;
            TextView tvStationName;

        }

    }














}
